import { Service } from 'egg';
import { User } from '../model/user';

export default class Oauth extends Service {

  // 根据 uid, provider 查询 oauth 表中有没有当前用户
  public async getUser({ id, provider }) {
    const { ctx } = this;
    try {
      const data = await ctx.model.Oauth.findOne({
        where: {
          uid: id,
          provider,
        },
        // 关联 User 返回 user 表中 id相同的用户信息
        include: [
          { model: User },
        ],
      });
      return data!.dataValues.user!.dataValues;
    } catch (e) {
      throw new Error('授权用户不存在');
    }
  }
  public async createOauth(data) {
    return await this.ctx.model.Oauth.create(data);
  }
}
